#include "HelloWorldScene.h"

USING_NS_CC;

unsigned int MyRand()
{
    static FILE* fp = fopen("/dev/urandom", "rb");
    
    if (fp)
    {
        unsigned int r;
        fread(&r, sizeof(r), 1, fp);
        return r;
    }
    return rand();
}

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    auto listener = EventListenerTouchOneByOne::create();
    listener->setSwallowTouches(true);
    /*
     listener->onTouchBegan = [=](cocos2d::Touch* touch,cocos2d::Event* event)
     {
     return true;
     };
     */
    listener->onTouchBegan = CC_CALLBACK_2(Layer::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(Layer::onTouchMoved, this);
    listener->onTouchEnded = CC_CALLBACK_2(Layer::onTouchEnded, this);
    
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Size winSize = Director::getInstance()->getWinSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    auto closeItem = MenuItemImage::create(
                                           "CloseNormal.png",
                                           "CloseSelected.png",
                                           CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
    
	closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
                                origin.y + closeItem->getContentSize().height/2));

    // create menu, it's an autorelease object
    auto menu = Menu::create(closeItem, NULL);
    menu->setPosition(Vec2::ZERO);
    this->addChild(menu, 1);

    /////////////////////////////
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label
    
    auto label = LabelTTF::create("Hello World", "Arial", 24);
    
    // position the label on the center of the screen
    label->setPosition(Vec2(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - label->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(label, 12345);

    // add "HelloWorld" splash screen"
    auto helloSprite = Sprite::create("HelloWorld.png");
    Size helloSize = helloSprite->getContentSize();
    // position the sprite on the center of the screen
    helloSprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
    helloSprite->setScale((float)visibleSize.width / helloSize.width, (float)visibleSize.height / helloSize.height);
    this->addChild(helloSprite);
    
    _mySprite = Sprite::create("Icon-72.png");
    Size spriteSize = _mySprite->getContentSize();
    
    float cx = origin.x + spriteSize.width / 2 + (float)MyRand() / 0xffffffff * (visibleSize.width - spriteSize.width);
    float cy = origin.y + spriteSize.height / 2 + (float)MyRand() / 0xffffffff * (visibleSize.height - spriteSize.height);
    CCLOG("Initial position: %f, %f\n", cx, cy);
    _mySprite->setPosition(Vec2(cx, cy));
    
    // add the sprite as a child to this layer
    this->addChild(_mySprite);
    
    this->schedule(schedule_selector(HelloWorld::moveMySprite), 0.3);
    this->schedule(schedule_selector(HelloWorld::updateGame));
    
    return true;
}

void HelloWorld::moveMySprite(float dt)
{
    Size spriteSize = _mySprite->getContentSize();
    
    float cx = (0.5 - (float)MyRand() / 0xffffffff) * 250;
    float cy = (0.5 - (float)MyRand() / 0xffffffff) * 200;
    auto moveByAction = MoveBy::create(1, Vec2(cx, cy));
    _mySprite->runAction(moveByAction);
}

void HelloWorld::updateGame(float dt)
{
    //CCLOG("updateGame: %f\n", dt);
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Size spriteSize = _mySprite->getContentSize();
    Vec2 pos = _mySprite->getPosition();
    
    float cx = 0, cy = 0;
    
    if (pos.x < spriteSize.width / 2)
        cx = (float)MyRand() / 0xffffffff * 250 / 2;
    else if (pos.x > visibleSize.width - spriteSize.width / 2)
        cx = - (float)MyRand() / 0xffffffff * 250 / 2;
    if (pos.y < spriteSize.height / 2)
        cy = (float)MyRand() / 0xffffffff * 200 / 2;
     else if (pos.y > visibleSize.height - spriteSize.height / 2)
        cy = - (float)MyRand() / 0xffffffff * 200 / 2;
    
    auto moveByAction = MoveBy::create(1, Vec2(cx, cy));
    _mySprite->runAction(moveByAction);
}

bool HelloWorld::onTouchBegan(Touch *touch, Event *unused_event)
{
    return true;
}

void HelloWorld::onTouchMoved(Touch *touch, Event *unused_event)
{
    
}

void HelloWorld::onTouchEnded(Touch *touch, Event *unused_event)
{
    Vec2 loc = touch->getLocation();
    CCLOG("Touch ended location: %f, %f", loc.x, loc.y);
    
    this->unschedule(schedule_selector(HelloWorld::moveMySprite));
    auto moveTo = MoveTo::create(1, loc);
    std::function<void()> func = std::bind(&HelloWorld::startSchedule, this);
    Sequence *sequence = Sequence::create(moveTo, CallFunc::create(func), NULL);
    _mySprite->stopAllActions();
    _mySprite->runAction(sequence);
}

void HelloWorld::startSchedule()
{
    this->schedule(schedule_selector(HelloWorld::moveMySprite), 0.3);
}

void HelloWorld::onTouchCancelled(Touch *touch, Event *unused_event)
{
    
}


void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
	MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
    return;
#endif

    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}
